import { IFeidaoAiNodejsComponent } from '@feidao/web/interfaces';

import render from '@feidao/web/atom/nodejs/render/render';
import nodejs from '@feidao/web/atom/nodejs/msg-b/nodejs';

import server_render from '../atom-n/server-render';
import { Params } from '../atom/params2query';
import p2q from '../atom/params2query';
import generate_query4render from '../atom/generate-query4render';
import generate_sort_fields from '../atom/generate-sort-fields';

import P01 from './P01';
import P02 from './P02';
import P04 from './P04';
import P03 from './P03';
import P05 from './P05';

const name2title = {
	// 'staff_name': '员工名称',
	// 'deptname': '部门',
	// 'name': '证照类型',
	// 'certificate': '证照名称',
	// 'confirm_date': '取证日期',
	// 'effectivedate': '生效日期',
	// 'staus': '状态',
	// 'purchase_right': '是否有期限限制',
	// 'enddate': '到期日期',
	// 'org_name': '发证机构',
	// 'memo': '备注'

	'work_plan': '计划名称',
	'employ_form': '培训形式',
	'deptname': '主办部门名称',
	'staff_name': '负责人名称',
	'total_people': '计划参培人数',
	'site': '培训地点',
	'org_name': '培训机构名称',
	'contact_name': '培训机构联系人',
	'course_name': '培训课程名称',
	'class_hour': '总课时',
	'start_time': '开课时间',
	'finish_time': '结课时间',
	'activity_budget': '培训预算',
	'resume_partment': '参培部门名称',
	'pub_user_name': '参培员工姓名',
	'branch_message': '培训机构信息'
};

function create_data_sort(fd: IFeidaoAiNodejsComponent) {
	try {
		const fields = ['work_plan',
			'employ_form',
			'deptname',
			'staff_name',
			'total_people',
			'site',
			'org_name',
			'contact_name',
			'course_name',
			'class_hour',
			'start_time',
			'finish_time',
			'activity_budget',
			'resume_partment',
			'pub_user_name',
			'branch_message'];
		const params = fd.data.params;
		delete params['page-no'];
		const data = generate_sort_fields(fd.data.url, fd.data.params as Params, fields);
		data.forEach((d) => {
			const field = d.field;
			render(fd.data.node, d, P02, field);
		});
	} catch (err) {
		console.error('------err', err);
	}
}

export default async function nba001(fd: IFeidaoAiNodejsComponent, ...args: any[]) {
	let page_no = fd.data.params['page-no'];
	if (!page_no) {
		page_no = 1;
	}
	let page_size = fd.data.params['page_size'];
	if (!page_size) {
		page_size = 20;
	}
	const q = p2q(fd.data.params as Params);
	const query = {
		filter: q.criteria,
		sort: q.sort,
		page_no,
		page_size
	};
	const data = generate_query4render(fd.data.url, fd.data.params as Params, name2title);
	render(fd.data.node, data, P01, 'P01');

	// 排序
	create_data_sort(fd);
	// 没有数据
	const res = await nodejs(fd.data.spaceid, "train_plan_find", query);
	// 无数据渲染P04
	if (res.dataArray.length == 0) {
		server_render(fd.data.node, 'P04', P04, '');
	} else {
		server_render(fd.data.node, 'P03', P03, res.dataArray);
	}

	res['page_size'] = page_size;
	render(fd.data.node, res, P05, 'P05');
}